/**
 * @fileOverview
 * A csv reporter that should be able to write a line of csv for every 'node' passed to it.
 * The intention is to be able to easily import a report from this plugin into a spreadsheet or database.
 * @author Martin 'Windgazer' Reurings, martin@windgazer.nl
 * @version 0.01.090701
 */

/**
 * @class
 * @constructor
 * 
 */
function CSVReport(/** string */path) {
	this.out = IO.open(path, false);
	this.out.write("Line,Function,Statements,Lines,Comment Lines,Comment%,Branches,Depth,Cyclomatic Complexity,Halstead Volume,Halstead Potential,Program Level,MI\n");
}

CSVReport.prototype = {
	/**
	 * Call this method before exiting to finalise the file.
	 */
	finalise: function() {
		this.out.flush();
		this.out.close();
	},
	/**
	 * If required this method will encode a value and surround it with double-quotes, as per csv standards.
	 */
	encode: function(/** string */value) {
		var val = value || "";
		/*if (isNumeric(val)) {
			return "=" + val;
		} else*/ if (val.indexOf && val.indexOf(";") + val.indexOf(",") >= 0) {
			val = val.replace(/([\\"])/gi, "\\$1");//Escape the escape character and double-quotes
			val = "\"" + val + "\"";//Surround with quotes and it should be 'safe' now :)
		}
		return val;
	},
	/**
	 * Adds a line with blank line-nr and filename as 'function'.
	 */
	addFileName: function(/** string */ fileName) {
		this.out.write("," + this.encode(fileName) + "\n");
	},
	/**
	 * Adds a line with a 'node's calculated values.
	 */
	addNode: function(/** node */ node, /** String */ filename) {
		var sn = node.name.replace("[[code]].", "");
		if (filename) {
			sn = sn.replace("[[code]]", filename);
		}
		var line = "";
		var sep = ",";
		line += node.lineStart;
		line += sep;
		line += this.encode(sn);
		line += sep;
		line += this.encode(node.s);
		line += sep;
		line += this.encode(node.lines());
		line += sep;
		line += this.encode(node.comments);
		line += sep;
		line += this.encode(Math.round(node.comments / (node.lines()) * 10000)/100 + "%");
		line += sep;
		line += this.encode(node.b);
		line += sep;
		line += this.encode(node.blockDepth);
		line += sep;
		line += this.encode(node.complexity());
		line += sep;
		line += this.encode(node.halsteadVolume());
		line += sep;
		line += this.encode(node.halsteadPotential());
		line += sep;
		line += this.encode(node.halsteadLevel());
		line += sep;
		line += this.encode(node.mi());
		line += "\n";
		this.out.write(line);
		this.out.flush();//In an attempt to keep the file intact when no finalise is called...
	}	
}

function isNumeric(n) 
{
	var re=/^\d+[\d\.\,\%]*$/; 
	return ( (null != n) && (typeof x == typeof 1) || re.test(n) );
}
